package cj.web.mall.controllers;

import java.util.Collections;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.paoding.rose.web.annotation.Param;
import net.paoding.rose.web.annotation.Path;
import net.paoding.rose.web.annotation.rest.Get;
import net.paoding.rose.web.annotation.rest.Post;
import net.paoding.rose.web.var.Model;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;

import cj.utils.Constants;
import cj.utils.DateUtils;
import cj.utils.sc.KDNiaoUtil;
import cj.web.BaseController;
import cj.web.mall.dao.OrderDAO;
import cj.web.mall.dao.UserDAO;
import cj.web.marriage.constants.MarriageSCOrderStatusEnum;
import cj.web.marriage.constants.SCShipperCodeEnum;
import cj.web.marry.dao.AppTokenDAO;

@Path("user")
public class UserController extends BaseController{
	@Autowired
	private UserDAO userDao;
	@Autowired
	private AppTokenDAO appTokenDao;
	@Autowired
	private OrderDAO orderDao;
	
	@Get("login")
	public String login(Model model, @Param("returnPage")String returnPage){
		if(returnPage != null && returnPage.length() > 0){
			model.add("returnPage", returnPage);
		}
		return "/views/marry/mall/login.vm";
	}
	
	@Post("register")
	public String register(@Param("phone")String phone, @Param("token")String token, HttpServletResponse response){
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		if( appTokenDao.queryToken(phone, token) > 0 ){
			if( userDao.isRegister(phone) == 0 ){
				userDao.register(phone);
			}
			setCookie(response, "phone", phone);
		}
		else{
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
		}
		
		return "@" + jo.toString();
	}
	
	@Post("logout")
	public String logout(HttpServletResponse response){
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		setCookie(response,"phone","");
		return "@" + jo.toString();
	}
	
	@Get("my")
	public String my(Model model, HttpServletRequest request){
		if(isLogin(request)){
			String phone = getCookieValueByName(request, "phone");
			int buyerId = userDao.getBuyerId(phone);
			model.add("buyerId", buyerId);
			model.add("phone", phone);
		}
		return "/views/marry/mall/my.vm";
	}
	
	@Get("addrchs")
	public String addressChoose(Model model, @Param("buyerId")int buyerId, @Param("addressId")String addressId){
		List<Map> Objs = userDao.getAddrByBuyerId(buyerId);
		model.add("Objs", Objs);
		model.add("buyerId", buyerId);
		model.add("addressId",addressId);
		return "/views/marry/mall/addressSelect.vm";
	}
	
	@Get("addruse")
	public String addressUse(Model model, @Param("buyerId")int buyerId){
		model.add("buyerId",buyerId);
		int cnt = userDao.addrCntByBuyerId(buyerId);
		if( cnt == 0){
			model.add("IsDefault", 1);
		}
		return "/views/marry/mall/addressUse.vm";
	}
	
	@Get("addrEditUse")
	public String addressEditUse(Model model, @Param("id")String addressId){
		List<Map> objs = userDao.getAddressById(addressId);
		if(objs != null && objs.size() > 0){
			model.add("Obj", objs.get(0));
		}
		return "/views/marry/mall/addressEditUse.vm";
	}
	
	@Post("addrUpdate")
	public String addressUpdate(@Param("id")String id, @Param("receiverName")String receiverName, @Param("receiverPhone")String receiverPhone, 
			@Param("address_picker")String address_picker, @Param("address")String address, @Param("isDefault")int isDefault){
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		String[] addrs = address_picker.split(" ");
		if(addrs != null && addrs.length > 0){
			String province = "";
			String city = "";
			String area = "";
			if( addrs.length == 2 ){
				province = addrs[0];
				city = addrs[1];
			}
			else if( addrs.length == 3 ){
				province = addrs[0];
				city = addrs[1];
				area = addrs[2];
			}
			List<Map> objs = userDao.getAddressById(id);
			if(objs != null && objs.size() > 0){
				int defaultFlag = Integer.parseInt(objs.get(0).get("isDefault").toString());
				if( defaultFlag == 0 && isDefault == 1){
					int buyerId = Integer.parseInt(objs.get(0).get("buyerId").toString());
					userDao.notDefaultByBuyerId(buyerId);
				}
				userDao.updateAddress(id, receiverName, receiverPhone, province, city, area, address, isDefault);
			}
			else{
				jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
			}
			
		}
		else{
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
		}
		
		return "@" + jo.toString();
	}
	
	@Get("addrlst")
	public String addressList(Model model, HttpServletRequest request){
		if( isLogin(request) ){
			int buyerId = getBuyerId(request);
			List<Map> Objs = userDao.getAddrByBuyerId(buyerId);
			model.add("Objs", Objs);
			model.add("buyerId", buyerId);
			return "/views/marry/mall/addressList.vm";
		}
		else{
			return "r:../user/login?returnPage=user/addrlst";
		}
		
	}
	
	@Get("addradd")
	public String addressAdd(Model model, @Param("buyerId")int buyerId){
		model.add("buyerId",buyerId);
		int cnt = userDao.addrCntByBuyerId(buyerId);
		if( cnt == 0){
			model.add("IsDefault", 1);
		}
		return "/views/marry/mall/addressAdd.vm";
	}
	
	@Post("addrCrt")
	public String addressCreate(@Param("buyerId")int buyerId, @Param("receiverName")String receiverName, @Param("receiverPhone")String receiverPhone, 
			@Param("address_picker")String address_picker, @Param("address")String address, @Param("isDefault")int isDefault){
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		String[] addrs = address_picker.split(" ");
		if(addrs != null && addrs.length > 0){
			String province = "";
			String city = "";
			String area = "";
			if( addrs.length == 2 ){
				province = addrs[0];
				city = addrs[1];
			}
			else if( addrs.length == 3 ){
				province = addrs[0];
				city = addrs[1];
				area = addrs[2];
			}

			if(isDefault == 1){
				userDao.notDefaultByBuyerId(buyerId);
			}
			
			String phone = userDao.getPhoneById(buyerId);
			int id = userDao.createAddress(buyerId, receiverName, receiverPhone, province, city, area, address, isDefault, phone);
			jo.put("id", id);
		}
		else{
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
		}
		
		return "@" + jo.toString();
	}
	
	@Get("addrEdit")
	public String addressEdit(Model model, @Param("id")String addressId){
		List<Map> objs = userDao.getAddressById(addressId);
		if(objs != null && objs.size() > 0){
			model.add("Obj", objs.get(0));
		}
		return "/views/marry/mall/addressEdit.vm";
	}
	
	@Post("addrDel")
	public String addressDelete(@Param("id")int addressId){
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		userDao.delAddrById(addressId);
		
		return "@" + jo.toString();
	}
	
	@Post("setDefault")
	public String setDefaultAddress(@Param("id")String addressId){
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		List<Map> objs = userDao.getAddressById(addressId);
		if(objs != null && objs.size() > 0){
			int buyerId = Integer.parseInt(objs.get(0).get("buyerId").toString());
			userDao.notDefaultByBuyerId(buyerId);
			userDao.setDefalut(addressId);
		}
		else{
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
		}
		
		return "@" + jo.toString();
	}
	
	@Get("orders")
	public String orders(Model model, HttpServletRequest request) throws Exception{
		if( isLogin(request) ){
			int buyerId = getBuyerId(request);
			List<Map> Objs = orderDao.getOrders(buyerId);
			if(Objs != null && Objs.size() > 0){
				for(Map obj : Objs){
					int orderId = Integer.parseInt(obj.get("id").toString());
					List<Map> items = orderDao.getItemsByOrderId(orderId);
					obj.put("Items", items);
				}
			}
			else{
				model.add("warning", "暂无订单");
				return "/views/marry/mall/orderNothing.vm";
			}
			
			model.add("Objs", Objs);
			model.add("Status", EnumSet.allOf(MarriageSCOrderStatusEnum.class));
			
			Map<String, String> config = getConfigSign(request);
			model.add("Config",config);
			return "/views/marry/mall/orders.vm";
		}
		else{
			return "r:../user/login?returnPage=user/orders";
		}
		
	}
	
	@Get("order")
	public String orderItem(Model model, @Param("id")int orderId, HttpServletRequest request) throws Exception{
		List<Map> objs = orderDao.getOrderById(orderId);
		if(objs != null && objs.size() > 0){
			List<Map> items = orderDao.getItemsByOrderId(orderId);
			objs.get(0).put("Items", items);
			String strDate = objs.get(0).get("createAt").toString();
			String createAt = DateUtils.formatDateStr(strDate, DateUtils.DATE_FULL_STR);
			objs.get(0).put("createAt", createAt);
			model.add("Obj", objs.get(0));
		}
		
		model.add("Status", EnumSet.allOf(MarriageSCOrderStatusEnum.class));
		
		Map<String, String> config = getConfigSign(request);
		model.add("Config",config);
		return "/views/marry/mall/order.vm";
	}
	
	@Post("cancel")
	public String cancel(@Param("id")int id){
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		List<Map> order = orderDao.getOrderById(id);
		if(order!=null && order.size()>0){
			int status = Integer.parseInt(order.get(0).get("status").toString());
			if(status==1){
				orderDao.cancelOrderById(id);
			}
		}
		
		return "@" + jo.toString();
	}
	
	@Get("aboutus")
	public String aboutUs(){
		return "/views/marry/mall/aboutUs.vm";
	}
	
	@Get("showLogistics")
	public String showLogistics(Model model, @Param("orderId")int orderId)
	{
		List<Map> orderObj = orderDao.getOrderById(orderId);
		
		if(orderObj!=null && orderObj.size()>0){
			model.add("id", orderObj.get(0).get("id").toString());
			//shipCode
			String expressCom = orderObj.get(0).get("expressCom").toString();
			String expressBill = orderObj.get(0).get("expressBill").toString();
			
			KDNiaoUtil api = new KDNiaoUtil();
			try {
				String result = api.getOrderTracesByJson(expressCom, expressBill);
				
				JSONObject jo = new JSONObject().fromObject(result);
				//物流路线
				JSONArray jslis = jo.getJSONArray("Traces");
				List<Map> list = JSONArray.toList(jslis, Map.class);// 过时方法
				Collections.reverse(list);
				
				model.add("list",list);
				
			} catch (Exception e) {
				e.printStackTrace();
			}
			
			model.add("expressName",SCShipperCodeEnum.getName(expressCom));
			model.add("expressCom",expressCom);
			model.add("expressBill", orderObj.get(0).get("expressBill").toString());
		}else{
			model.add("id", "");
			model.add("expressCom", "");
			model.add("expressBill", "");
			model.add("list","");
		}
		
		return "/views/marry/mall/logistics.vm";
	}
	
	private int getBuyerId(HttpServletRequest request){
    	String phone = getCookieValueByName(request, "phone");
		int buyerId = userDao.getBuyerId(phone);
		
		return buyerId;
    }
}
